package com.telnikoff.gf;

import java.util.HashMap;
import java.util.Map;

import javax.swing.Action;

public class DefaultGfMenuFactory implements GfMenuFactory
{
	private final GfMenuNode n;
	private final Map <String, GfMenuFactory> map;
	
	protected DefaultGfMenuFactory(GfMenu n)
	{
		this.n = n;
		this.map = new HashMap<String, GfMenuFactory>();
		map.put("/", this);
	}
	
	private DefaultGfMenuFactory(GfMenuBranch n, Map<String, GfMenuFactory> map, String parentName)
	{
		this.n = n;
		this.map = map;
		map.put(parentName+"/"+n.getName(), this);
	}

	private GfMenuFactory addMenu(String name) 
	{
		if (n instanceof GfMenu)
		{
			GfMenu menu = (GfMenu)n;
			GfMenuBranch branch = new DefaultGfMenuBranch(name);
			menu.add(branch);
			return new DefaultGfMenuFactory(branch, map, "");
		}
		else
		{
			GfMenuBranch parent = (GfMenuBranch)n;
			GfMenuBranch child  = new DefaultGfMenuBranch(name);
			parent.add(child);
			return new DefaultGfMenuFactory(child, map, parent.getName());
		}
	}

	private GfMenuFactory addItem(Action a) 
	{
		if (n instanceof GfMenu)
		{
			return this;
		}
		else
		{
			GfMenuBranch parent = (GfMenuBranch)n;
			GfMenuLeaf   child  = new DefaultGfMenuLeaf(a);
			parent.add(child);
			return this;
		}
	}

	@Override
	public GfMenuFactory get(String path) 
	{
		return map.get(path);
	}

	@Override
	public GfMenuFactory addItem(String path, Action a) 
	{
		if (null == path || path.length() == 0 || path.equals("/"))
			throw new IllegalArgumentException("Path must start with '/' "+
				"and have at least one element.");
		
		String[] str = path.split("/");
		String combined = "";
		DefaultGfMenuFactory f = (DefaultGfMenuFactory)get("/");
		for (String s : str)
		{
			if (s.length() == 0)
				continue;
			
			combined += "/" + s;

			if (null == get(combined))
			{
				f = (DefaultGfMenuFactory)f.addMenu(s);
			}
			else
				f = (DefaultGfMenuFactory)get(combined);
		}
		return f.addItem(a);
	}

}